package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义超时订单处理类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每一分钟检查一次超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "* */5 * * * *")
    public void processTimeoutOrder() {
        log.info("超时订单检查：{}", LocalDateTime.now());
        //select * from orders where status = ? and order_time > (现在-15分钟)
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //查出所有超时订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        //若不为空
        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                //更新订单状态为已取消，补充取消原因，取消时间
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 每天凌晨一点检查一次派送中订单
     */
    @Scheduled(cron="0 0 1 * * ?")
//    @Scheduled(cron = "* */5 * * * *")
    public void processDeliveryOrder(){
        log.info("派送中订单检查：{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //查出所有派送中订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        //若不为空
        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                //更新订单状态为已完成
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
